articles

home / developersection / articles / validation using data annotation using entity framework

Validation using Data Annotation using entity framework

Manish Kumar 4141 19-Jan-2017

Data annotation is for adding extra meaning to the data. We use attribute for data annotation. There are many attribute which we use for data annotation. We use data annotation for data validating, we can validate our field by data annotation by simply adding attribute.

By data annotation we can validate our field in the UI and by using Display attribute we can specify that how data from model is displayed in view or UI. 

We use system.componentmodel.DataAnnotation namespace for using attribute of data annotation.

Now we will take an example for data annotation.

When we are working with data first approach. We cannot put our validation in the self-generate class from the EF because when we change our database table our validation will lose so the right way is For  data annotation to create a class in model folder and name it Metadata’s

using System;
using System.Collections.Generic;
using System.Linq;                           
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
    public class EmpDetailMetaData
    {
      
        [Required(ErrorMessage = "UserName Name is required")]
        public string UserName { get; set; }
        [Required(ErrorMessage = "FName Name is required")]
        public string FName { get; set; }
        [Required(ErrorMessage = "Email is required")]
        public string Email { get; set; }
        [Required(ErrorMessage = "Mobile is required")]
        public string Mobile { get; set; }
    }
}


And another class name it partialclass

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
 
namespace Demo.Models
{     
        [MetadataType(typeof(EmpDetailMetaData))]
        public partial class EmpDetail
        {
        }
}


In the above metadata class we have use required attribute

Now in the controller we do the logic for validation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Demo.Models;
 
 
namespace Demo.Controllers
{
    public class HomeController : BaseController
    {                  public ActionResult Index()
        {
            ViewBag.Users = Uow.EmpDetail.SelectAll();      
           
            return View();
        }
 
    [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(EmpDetail model)
        {
            if (ModelState.IsValid)
            {
                if (model.Id == 0)
                {
                    Uow.EmpDetail.Insert(model);
 
                }
                else
                {
                    var data = Uow.EmpDetail.SelectByID(model.Id);
                    if (data == null)
                        Uow.EmpDetail.Insert(model);
                    else
                        Uow.EmpDetail.Update(model);
                }
            }
                ViewBag.Users =Uow.EmpDetail.SelectAll();
                return PartialView("UserList");          
         
        }             [HttpPost]
        public ActionResult Delete(int Id)
        {
            Uow.EmpDetail.Delete(Id);         
            ViewBag.Users = Uow.EmpDetail.SelectAll();           
            return PartialView("UserList");
        }     
        public ActionResult Edit(int Id)
        {
            var data = Uow.EmpDetail.SelectByID(Id);
            return Json(data, JsonRequestBehavior.AllowGet);
        }
      
 
    }
}
 

Now int the add view for for index method.
@{

    ViewBag.Title = "Index";
}
 
@*<script src="~/Scripts/jquery-3.1.1.min.js"></script> *@
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.2/jquery.validate.unobtrusive.js"></script>
@using (Ajax.BeginForm("index", "Home", new AjaxOptions
{
    HttpMethod = "POST"
    UpdateTargetId = "target",
    OnSuccess = "updateSuccess"
}))
{
 
        <center><h2>Registration Form</h2></center>
     @Html.ValidationSummary(true
        <hr />
       <div>
            <center> <table border="0"  width="70%" cellspadding="0" cellspacing="0">
        <tr>
             <td><label id="label1">User Name</label>
                @Html.HiddenFor(x => x.Id, new {@Value=0 })
            </td>
              <td>@Html.TextBoxFor(x => x.UserName)
                  @Html.ValidationMessageFor(m => m.UserName)
              </td>
            <td><label id="label2">Father Name</label></td>
              <td>@Html.TextBoxFor(x => x.FName)
                  @Html.ValidationMessageFor(m => m.FName)
              </td>
        </tr>
       <tr>
            <td><label id="label3">Email</label></td>
              <td>@Html.TextBoxFor(x => x.Email)
                  @Html.ValidationMessageFor(m=> m.Email)
              </td>
            <td><label id="label4">Mobile</label></td>
              <td>@Html.TextBoxFor(x=> x.Mobile)
                  @Html.ValidationMessageFor(m => m.Mobile)
              </td>
        </tr>
       <tr>
         <td colspan="2"> <br /> <center>
               <input type="submit" value="Submit" /></center>
           </td>
       </tr>
    </table></center>
        </div>
         
 
}

 

You can also visit these related articles and blogs

Crud operation in mvc using data annotation with entity framework

Upload File using Model Validation in ASP.NET MVC


Updated 17-Nov-2018

Leave Comment

Comments

Liked By